# coding=utf-8

import requests
import json
from common.caseLog import Log
from common.common_ssh_mysql import Connect_Mysql
from common.readConfig import read
from common.create_time import time_create
import time


class PublicRequest():
    list_dict = {}
    def __init__(self, host, user, password, db, port=None, ssh_host=None, ssh_mysql=None):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = db
        self.ssh_host = ssh_host
        self.ssh_mysql = ssh_mysql
        self.log = Log()

    def sql_result(self, sql):
        '''数据库查询操作'''
        conn = Connect_Mysql(self.host, self.user, self.password, self.db)
        if 'select' in sql.lower():
            result = conn.select_table(sql)
            self.log.info(result)
        else:
            result = conn.commit_table(sql)
        return result

    def date_params_replace(self, data_parameter, sql):
        '''参数替换'''
        try:
            data_parameter = data_parameter.split(',')  # 字符串转列表
            conn = Connect_Mysql(
                host=self.host,
                user=self.user,
                password=self.password,
                db_name=self.db,
            )
            if 'select' in sql.lower():
                result = conn.select_table(sql)
                self.log.info(result)
            else:
                result = conn.commit_table(sql)
            date_data = []
            for i in data_parameter:
                date = result[0][i]
                date_data.append(date)
            self.log.info(date_data)
            return tuple(date_data)
        except Exception as e:
            self.log.error(e)

    def data_time_replace(self, data, data_time):
        '''时间参数替换'''
        try:
            data_time = data_time.split(',')  # 字符串转列表
            stime, etime = time_create(int(data_time[-1]))
            for i in data_time:
                if i == 'stime':
                    data = data.replace(i, stime)  # 替换
                elif i == 'etime':
                    data = data.replace(i, etime)  # 替换
            return data
        except Exception:
            return data
    @classmethod
    def code_only_replace(cls, data, code_only):
        '''code参数替换'''
        try:
            str = repr(int(time.time()))
            data_time = code_only.split(',')  # 字符串转列表
            for i in data_time:
                data = data.replace(i, str)  # 替换
            return data
        except Exception:
            return data

    def index_variable(self, lists, reposen):
        '''提取接口返回值'''
        if len(lists) == 1:
            table = lists[0]
            ddd = reposen[table]
            return ddd
        else:
            for i in lists:
                try:
                # if len(i) == 1:
                    reposen = reposen[int(i)]
                except Exception as e:
                    if isinstance(i, int):
                        reposen = reposen[int(i)]
                    else:
                        reposen = reposen[i]
                lists.remove(i)
                return self.index_variable(lists, reposen)

    def data_var(self, variable, data):
        # 循环替换data中的值
        if len(variable) == 1:
            i = variable[0]
            index_data = self.list_dict[i]
            data = data.replace(i, index_data)  # 替换
            return data
        else:
            for i in variable:
                index_data = self.list_dict[i]
                data = data.replace(i, index_data)  # 替换
                variable.remove(i)
                return self.data_var(variable, data)

    def variable_save(self, variable, get_variable, result):
        '''将返回值保存到字典中'''
        list_index_var = variable.split(',')  # 字符串转列表
        list_index_get_var = get_variable.split(',')  # 字符串转列表
        list_dict_var = dict(zip(list_index_var, list_index_get_var))
        self.log.debug(list_dict_var)
        for var, get_var in list_dict_var.items():
            list_index = get_var.split('.')  # 字符串转列表
            try:
                self.list_dict[var] = self.index_variable(list_index, result.json())
            except Exception as e:
                self.log.error(e)
        return self.list_dict

    def variable_put(self, variable, data):
        '''根据要求提取保存在字典中的返回值'''
        try:
            lists = variable.split(',')  # 字符串转列表
            return self.data_var(lists, data)
        except Exception as e:
            self.log.error(e)

    def publicSend(self, host, method, api, token,
                   auth, data_parameter=None, url_parameter=None,
                   data=None, sql=None, data_time=None,
                   url_time=None, code_only=None,
                   api_code_only=None, variable=None,
                   get_variable=None):
        # r = requests.Session()
        # r.mount('http://', HTTPAdapter(max_retries=3))
        # r.mount('https://', HTTPAdapter(max_retries=3))
        if auth:
            self.log.info('获取登录状态')
            h = {
                "Authorization": "Bearer {}".format(token),
                "TENANT-ID": "-1"
            }

        else:
            self.log.info('不获取登录状态')
            h = {
            }
        result = ''
        if method.lower() == 'get':
            '''判断请求方式进行选择请求'''
            if variable and get_variable == '':
                api = self.variable_put(variable, api)
            if url_time:
                api = self.data_time_replace(api, data_time)
            if api_code_only:
                api = self.code_only_replace(api, code_only)
            if url_parameter:
                date_format = self.date_params_replace(url_parameter, sql)
                result = requests.get(host + api % date_format, headers=h)
            else:
                result = requests.get(host + api, headers=h)
            if get_variable:
                self.variable_save(variable, get_variable, result)
        elif method.lower() == 'post':
            '''判断请求方式进行选择请求'''
            if variable and get_variable == '':
                data = self.variable_put(variable, data)
            if data_time:
                data = self.data_time_replace(data, data_time)
            if code_only:
                data = self.code_only_replace(data, code_only)
            if data_parameter:
                date_format = self.date_params_replace(data_parameter, sql)
                # elif code_only != '':
                #     code_time = int(time.time())
                #     date_format = repr(code_time)
                # date_format = date_params_replace(data_parameter, sql)
                result = requests.post(host + api,
                                       headers=h,
                                       json=json.loads(data % date_format),
                                       timeout=5)
            else:
                if data is None or data == '':
                    if url_parameter != '':
                        date_format = self.date_params_replace(url_parameter, sql)
                        result = requests.post(host + api % date_format, headers=h)
                    else:
                        result = requests.post(host + api, headers=h, timeout=5)
                else:
                    result = requests.post(host + api, headers=h, json=json.loads(data), timeout=5)
            # if get_variable:
            #     self.variable_save(variable, get_variable, result)


        elif method.lower() == 'patch':
            '''判断请求方式进行选择请求'''
            if variable and get_variable == '':
                data = self.variable_put(variable, data)
            if data_time:
                data = self.data_time_replace(data, data_time)
            if data_parameter:
                date_format = self.date_params_replace(data_parameter, sql)
                result = requests.patch(host + api, headers=h, json=json.loads(data % date_format), timeout=5)
            else:
                if data is None or data == '':
                    result = requests.patch(host + api, headers=h, timeout=5)
                else:
                    result = requests.patch(host + api, headers=h, json=json.loads(data), timeout=5)
        elif method.lower() == 'delete':
            '''判断请求方式进行选择请求'''
            if variable and get_variable == '':
                data = self.variable_put(variable, data)
            if data_parameter:
                date_format = self.date_params_replace(data_parameter, sql)
                result = requests.delete(host + api, headers=h, json=json.loads(data % date_format), timeout=5)
            elif url_parameter:
                date_format = self.date_params_replace(url_parameter, sql)
                result = requests.delete(host + api % date_format, headers=h, timeout=5)
            else:
                if data is None or data == '':
                    result = requests.delete(host + api, headers=h, timeout=5)
                else:
                    result = requests.delete(host + api, headers=h, json=json.loads(data), timeout=5)
        return result
        # except Exception as e:
        #     log.error(e)


if __name__ == '__main__':
    a = '{"starttime": "code", "endtime": "code1"}'
    c = "code,code"
    b = "stime,etime,7"
    # myself = PublicRequest('ooo')
    # print(myself.data_time_replace(a, b))
    # print(int(time.time()))
    lll = PublicRequest.code_only_replace(a, c)
    print(lll)
